package ce.authentication;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.cs.um.UMService;

public class CeAuthenticationFilter implements Filter {

	public static final String CE_LOGIN_INFO = "ce.session.logininfo";
	private String mainPage = "/ipc/main.html";
	private UMService service;  // 处理登录service
	private StringBuffer error ;
	public void init(FilterConfig filterConfig) {
		final String mp = filterConfig.getInitParameter("mainPage");
		if (mp != null)
			mainPage = mp;
	}
	public void initError(){
		error = new StringBuffer();
		//error.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
		error.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\">");
		error.append("<head><title>登录系统失败</title>"
					 +"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />"
					 +"<style type=\"text/css\">"					 
					 +"#content {clear:both; padding:1px 0; margin:0 25px 2em;}"
					 +".errors {margin-top: 52px;font-size: 14px;border:1px dotted #d21033; background:#fed url(http://172.168.1.19:8080/cas/images/error.gif) no-repeat 20px 18px; color:#d21033;padding: 0 20px 20px 100px;}"
					 +"</style></head>"
					 +"<body id=\"cas\" class=\"fl-theme-iphone\">"
					 +"<div class=\"flc-screenNavigator-view-container\">"
					 +"	<div class=\"fl-screenNavigator-view\">"
					 +"<div id=\"header\" class=\"flc-screenNavigator-navbar fl-navbar fl-table\">"
					 +"	</div><div id=\"content\" class=\"fl-screenNavigator-scroll-container\"><div id=\"msg\" class=\"errors\">"
					 +"	<h2>登录失败</h2><p>您已经成功登录CAS系统，但您没有本系统的使用权限！</p><p>您可以清除浏览器缓存重试。如有疑问，请联系管理员。</p>" 
					 +"</div></div></div></div></body></html>");
	}

	
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
    		FilterChain filterChain) throws IOException, ServletException {
    	final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
    	final HttpSession session = request.getSession();
    	
    	Object loginInfo = session.getAttribute(CE_LOGIN_INFO);
		String loginUser = request.getRemoteUser();
    	if (loginUser != null && loginInfo == null) {
    		try {
    			final HashMap<String, Object> map = new HashMap<String, Object>();
    			map.put("user", loginUser);
				Object[] objs = service.login(map, request, true);
	    		session.setAttribute(CE_LOGIN_INFO, objs);
	    		// 进入主界面
	    		response.sendRedirect(request.getContextPath() + mainPage);
	    		return;
			} catch (Exception e) {
				response.setContentType("text/html;charset=utf-8");  
	    		initError();
				response.getWriter().write(error.toString());
				e.printStackTrace();
				return;
			}
    	} else if (loginInfo != null && "GetCeLoginInfo".equals(request.getParameter("Method"))) {
    		response.setContentType("text/xml;charset=utf-8"); 
    		response.getWriter().write(Arrays.toString((Object[])loginInfo));
    		return;
    	}
    	filterChain.doFilter(request, response);
	}
	
	// empty implementation as most filters won't need this.
    public void destroy() {
        // nothing to do
    }

	public void setService(UMService service) {
		this.service = service;
	}

}
